import React, {useRef, useState} from "react";
import { Input, InputRef } from "antd";
import st from './editable-text.module.css'

interface PropsType {
    placeholder?: string
    style?: React.CSSProperties
    dir?: 'ltr' | 'rtl'
    onTextChange?: (value: string) => void
    defaultText?: string
}

export const EditableText: React.FC<PropsType> = ({
    placeholder = '请输入',
    style = {},
    dir = 'ltr',
    onTextChange = () => {},
    defaultText= ''
}) => {
    const inpRef = useRef<InputRef>(null)
    const [value, setValue] = useState(defaultText)
    const [displayInput, setDisplayInput] = useState(false)
    function onClickText() {
        setDisplayInput(true)
        Promise.resolve().then(() => {
            inpRef.current!.focus({ cursor: 'end' })
        })
    }
    function getJustifyContent() {
        return dir === 'rtl' ?  'end' : 'start';
    }
    if (displayInput) {
        return <div className={st['editable-text']} style={{justifyContent: getJustifyContent()}}>
            <Input ref={inpRef}
                   value={value}
                   size={'small'}
                   onKeyUp={(e) => {
                       const isPressEnter = e.keyCode === 13
                       if (isPressEnter) {
                           setDisplayInput(false)
                           onTextChange(value)
                       }
                   }}
                   onChange={(e) => setValue(e.target.value)}
                   onBlur={e => {  setDisplayInput(false); onTextChange(value) } }
                   placeholder={placeholder} dir={dir}></Input>
        </div>
    }

    return <div className={st['editable-text']} style={{justifyContent: getJustifyContent()}}>
        <span style={style} onClick={() => onClickText() }>{value}</span>
        {!value ? <span onClick={() => onClickText()} className={st['et-placeholder']}>{placeholder}</span> : null }
    </div>
}
